import { getRoomListUsingPost } from '@/services/pikimbi/chatRoomController';
import { RobotFilled } from '@ant-design/icons';
import { useModel } from '@umijs/max';
import { Avatar, Card, List, Typography, message, theme } from 'antd';
import React, { useEffect, useState } from 'react';
import { request } from './../../app.tsx';

const { Title, Text } = Typography;
const { useToken } = theme;

// 类型定义
interface ChatMessage {
  id: string;
  sender: 'USER' | 'AI';
  content: string;
  createTime: string;
}

interface ChatRoom {
  id: string;
  roomBrief: string;
  chatMessagesList: ChatMessage[];
}

interface PageRequest {
  current?: number;
  pageSize?: number;
  sortField?: string;
  sortOrder?: string;
}

interface ChatRoomQueryRequest extends PageRequest {
  userId?: string;
}

const ChatHistoryPage: React.FC = () => {
  const { token } = useToken();
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState ?? {};
  const [selectedRoom, setSelectedRoom] = useState<ChatRoom | null>(null);
  const [rooms, setRooms] = useState<ChatRoom[]>([]);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [pageParams, setPageParams] = useState({
    current: 1,
    pageSize: 5, // 每页5条
  });

  const { baseURL } = request;

  const loadMore = async () => {
    if (loading || !hasMore) return;
    setLoading(true);
    try {
      const params: ChatRoomQueryRequest = {
        ...pageParams,
        userId: currentUser?.data?.id,
      };

      const res = await getRoomListUsingPost(params);

      if (res.code === 0) {
        setRooms([...rooms, ...(res.data?.records || [])]);
        setHasMore(pageParams.current * pageParams.pageSize < (res.data?.total || 0));
        setPageParams((prev) => ({
          ...prev,
          current: prev.current + 1,
        }));
      } else {
        message.error(res.message || '请求失败');
      }
    } catch (error) {
      message.error('请求异常');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (rooms.length > 0 && !selectedRoom) {
      setSelectedRoom(rooms[0]);
    }
  }, [rooms]);

  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    const { scrollTop, clientHeight, scrollHeight } = e.currentTarget;
    if (scrollHeight - scrollTop <= clientHeight + 100) {
      loadMore();
    }
  };

  useEffect(() => {
    loadMore();
  }, []);

  return (
    <Card
      bordered={false}
      bodyStyle={{
        padding: 0,
        display: 'flex',
        height: '74vh',
        background: token.colorBgContainer,
      }}
    >
      {/* 左侧房间列表 */}
      <div
        style={{
          width: 320,
          borderRight: `1px solid ${token.colorBorderSecondary}`,
          display: 'flex',
          flexDirection: 'column',
        }}
      >
        <div style={{ padding: 16, borderBottom: `1px solid ${token.colorBorderSecondary}` }}>
          <Text strong style={{ fontSize: 16 }}>
            聊天记录
          </Text>
        </div>
        <div
          style={{
            flex: 1,
            overflowY: 'auto',
            padding: '0 16px',
          }}
          onScroll={handleScroll}
        >
          <List
            dataSource={rooms}
            renderItem={(room) => (
              <Card
                hoverable
                onClick={() => setSelectedRoom(room)}
                style={{
                  margin: '8px 0',
                  background: selectedRoom?.id === room.id ? token.colorPrimaryBg : 'transparent',
                  borderColor:
                    selectedRoom?.id === room.id
                      ? token.colorPrimaryBorder
                      : token.colorBorderSecondary,
                  cursor: 'pointer',
                  transition: 'all 0.3s',
                }}
                bodyStyle={{ padding: 12 }}
              >
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <Text
                    ellipsis
                    style={{
                      color: token.colorText,
                      lineHeight: 1.5,
                    }}
                  >
                    {room.roomBrief}
                  </Text>
                </div>
              </Card>
            )}
          />
        </div>
      </div>
      {console.log(selectedRoom, '1111111111111')}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
        <div
          style={{
            borderBottom: `1px solid ${token.colorBorderSecondary}`,
            background: token.colorBgElevated,
            textAlign: 'center',
          }}
        >
          <Title level={5}>
            详细对话
            <div>{new Date(selectedRoom?.chatMessagesList[0]?.createTime).toLocaleString()}</div>
          </Title>
        </div>
        <div
          style={{
            flex: 1,
            padding: 24,
            overflowY: 'auto',
            background: token.colorBgLayout,
          }}
        >
          {selectedRoom ? (
            <List
              dataSource={selectedRoom.chatMessagesList}
              renderItem={(msg) => (
                <div
                  style={{
                    display: 'flex',
                    gap: 12,
                    marginBottom: 16,
                    flexDirection: msg.sender === 'USER' ? 'row-reverse' : 'row',
                  }}
                >
                  <div style={{ flexShrink: 0 }}>
                    {msg.sender === 'AI' ? (
                      <Avatar
                        icon={<RobotFilled style={{ fontSize: '20px' }} />}
                        size="large"
                        style={{
                          backgroundColor: '#1890ff',
                          fontSize: '20px',
                        }}
                      />
                    ) : (
                      <Avatar
                        src={
                          currentUser?.data?.userAvatar &&
                          `${baseURL}/api/${currentUser.data.userAvatar}`
                        }
                        style={{ backgroundColor: token.colorPrimaryBg }}
                      />
                    )}
                  </div>
                  <div
                    style={{
                      maxWidth: '70%',
                      background:
                        msg.sender === 'USER' ? token.colorPrimary : token.colorBgElevated,
                      color: msg.sender === 'USER' ? token.colorWhite : token.colorText,
                      padding: '12px 16px',
                      borderRadius: 8,
                      boxShadow: token.boxShadowSecondary,
                      border:
                        msg.sender === 'AI' ? `1px solid ${token.colorBorderSecondary}` : 'none',
                    }}
                  >
                    <div style={{ whiteSpace: 'pre-wrap' }}>{msg.content}</div>
                    <div
                      style={{
                        marginTop: 8,
                        fontSize: 12,
                        color:
                          msg.sender === 'USER'
                            ? 'rgba(255,255,255,0.7)'
                            : token.colorTextSecondary,
                      }}
                    ></div>
                  </div>
                </div>
              )}
            />
          ) : (
            <div
              style={
                {
                  /* 空状态 */
                }
              }
            />
          )}
        </div>
      </div>
    </Card>
  );
};

export default ChatHistoryPage;
